<template>
  <div class="context-menu-command" v-if="visible" :style="positionStyle">
    <ul>
      <li
        @click="handleCommandClick(item)"
        v-for="item in commandList"
        :key="item.command">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
import { getTargetParentNode } from '~/util'

export default {
  name: 'ContextMenu',
  props: {
    commandList: {
      type: Array,
      default: () => []
    },
    contextPosition: {
      type: Object
    }
  },
  data () {
    return {
      visible: false
    }
  },
  created () {},

  methods: {
    handleCommandClick (commanItem) {
      this.$emit('command-click', commanItem.command)
      this.visible = false
    }
  },

  computed: {
    positionStyle () {
      if (!this.contextPosition) return {}
      const { left, top } = this.contextPosition
      return {
        left: left + 'px',
        top: top + 'px'
      }
    }
  },

  watch: {
    contextPosition: {
      handler (newVal) {
        if (newVal) {
          this.visible = true
        }
      },
      deep: true
    },

    visible (newVal) {
      if (!newVal) {
        document.documentElement.onclick = null
      } else {
        document.documentElement.onclick = (e) => {
          if (!getTargetParentNode(e.target, 'context-menu-command')) {
            this.visible = false
          }
        }
      }
    }
  },

  beforeDestroy () {
    document.documentElement.onclick = null
  }
}
</script>
<style lang="less" scoped>
.context-menu-command {
  position: fixed;
  z-index: 99999;
  background: #fff;
  box-shadow: 0 0 10px 2px rgba(0,0,0,0.1);
  border-radius: 6px;
  ul {
    margin: 0;
    padding: 8px 4px;
    list-style: none;
    width: 130px;
    li {
      line-height: 30px;
      padding: 0 12px;
      font-size: 13px;
      cursor: pointer;
      border-radius: 4px;
      color: #333;
      margin: 4px 0;
      &:hover {
        background-color: rgb(242,243,243);
      }
    }
  }
}
</style>
